#include "client_manager.h"
#include <QHostAddress>
ClientManager * ClientManager::m_instance = nullptr;
QMutex ClientManager::m_mutex;

ClientManager & ClientManager::getInstance()
{
    if(nullptr == m_instance){
        QMutexLocker lock(&m_mutex);
        if(nullptr == m_instance){
            m_instance = new ClientManager();
        }
    }

    return * m_instance;
}

void  ClientManager::addClient(QHostAddress  ip,quint16 port)
{
    m_clientList.insert( qMakePair( ip ,port) );
}

void ClientManager::sendData(QUdpSocket &udp, const QByteArray &arr)
{
    foreach (  auto pair,   m_clientList)
    {
        //客户端的IP与端口， first代表std::pair的第一个值， second代表第二个
        QHostAddress addr = pair.first;
        quint16 port = pair.second;
        //发送数据，需要指定接收方的IP与端口
        udp.writeDatagram(arr,  addr, port);
    }

}

int ClientManager::clientCount()
{
    return m_clientList.size();
}

void ClientManager::closeAllClients()
{
    //清空客户端列表
    m_clientList.clear();
}
